package com.example.kass.config;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.stereotype.Controller;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.HashSet;
import java.util.Iterator;

/**
 * 全局异常处理
 */
@Slf4j
@ControllerAdvice
@Controller
public class FaultBarrier {

    /**
     * @Title: handleConstraintViolationException
     * @Description: Post方式参数验证异常
     */
    @ResponseBody
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Object methodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e) {
        log.info("POST参数校验结果异常处理");
        ObjectError objectError = e.getBindingResult().getAllErrors().get(0);
        return objectError.getDefaultMessage();
    }

    /**
     * @Title: handleConstraintViolationException
     * @Description: Get方式参数验证异常
     */
    @ExceptionHandler(ConstraintViolationException.class)
    @ResponseBody
    public Object handleConstraintViolationException(ConstraintViolationException ex) {
        log.info("GET参数校验结果异常处理");
        // 获取所有错误信息
        HashSet<ConstraintViolation<?>> set = (HashSet<ConstraintViolation<?>>) ex.getConstraintViolations();
        Iterator<ConstraintViolation<?>> iterator = set.iterator();
        if (iterator.hasNext()) {
            ConstraintViolation<?> next = iterator.next();
            // 只取一个异常信息返回
            String msg = next.getMessageTemplate();
            //返回自定义信息格式
            return msg;
        }
        return "参数错误";
    }


    /**
     * 系统异常拦截
     */
    @ResponseBody
    @ExceptionHandler(Exception.class)
    public Object exception(Exception e, HttpServletRequest request) {
        log.error(ExceptionUtils.getStackTrace(e), e);
        return "异常！！！";
    }


}